<?php

class Application_Model_CommentMapper {

    protected $_dbTable;

    public function setDbTable($dbTable) {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }

    public function getDbTable() {
        if (null === $this->_dbTable) {
            $this->setDbTable('Application_Model_DbTable_Comment');
        }
        return $this->_dbTable;
    }

    public function save(Application_Model_Comment $comment) {
        $data = array(
            'id' => $comment->id(),
            'user_id' => $comment->user_id(),
            'time' => $comment->time(),
            'content' => $comment->content(),
        );

        if ($data["time"] === null) {
            unset ($data["time"]);
        }

        if (null === ($id = $comment->id())) {
            unset($data['id']);
            return $this->getDbTable()->insert($data);
        } else {
            $this->getDbTable()->update($data, array('id = ?' => $id));
            return $id;
        }
    }

    public function find($id) {
        $result = $this->getDbTable()->find($id);
        if (0 == count($result)) {
            return null;
        }
        $row = $result->current();
        $user_mapper = new Application_Model_UserMapper();
        $user = $user_mapper->find($row->user_id);
        $return = new Application_Model_Comment($row->id, $row->user_id, $row->time, $row->content);
        $return->set_user($user);
        return $return;
    }

    public function fetchAll() {
        $resultSet = $this->getDbTable()->fetchAll();
        $entries = array();
        foreach ($resultSet as $row) {
            $entry = new Application_Model_Comment($row->id, $row->user_id, $row->time, $row->content);
            $entries[] = $entry;
        }
        return $entries;
    }

    public function fetchPaginated($page) {
        $resultSet = $this->getDbTable()->fetchAll(NULL, 'time DESC', 7, $page * 7);
        $umapper = new Application_Model_UserMapper();
        $entries = array();
        foreach ($resultSet as $row) {
            $entry = new Application_Model_Comment($row->id, $row->user_id, $row->time, $row->content);
            $entry->set_user($umapper->find($entry->user_id()));
            $entries[] = $entry;
        }
        return $entries;
    }

    public function linkGroup($id, $gid) {
        $tbl = new Application_Model_DbTable_CommentLink();
        return $tbl->insert(array("comment_id" => $id, "group_id" => $gid));
    }

    public function linkElement($id, $eid) {
        $tbl = new Application_Model_DbTable_CommentLink();
        return $tbl->insert(array("comment_id" => $id, "element_id" => $eid));
    }
}
